import Taro,{ useLoad } from '@tarojs/taro';
import { View, Button, Text, Input } from '@tarojs/components';
import { useEffect, useState } from 'react';
import './index.scss';
import { request,whRequest } from '@/utils/request'

import { getGlobalData } from '@/globalData';

let openid :string = ''
let unionid:string = ''
let custPhone:string = ''
let userInfo:any = {}
let appid = getGlobalData('appid')
export default function UserDialogLogin(props) {
  
  const [visible, setVisible] = useState(props.visible)
  let inviteOptions = Taro.getStorageSync('inviteObj') || {}
  // console.log('inviteOptions:',inviteOptions)
  let fromPath = '/'+Taro.getCurrentPages()[0].route || '/pages/index/index'
  useEffect(() => {
    setVisible(props.visible)
  },[props.visible])
  
  async function getPatientInfo(patientId) {
    return new Promise((resolve) => {
      if (patientId) {
        whRequest({
          url: `/patient/${patientId}`,
          data: {},
          method: 'GET',
          success: (data) => {
            let { realNameAuthenticationPassed } = data
            Taro.setStorageSync('_patientInfo', data)
            Taro.setStorageSync('hasRealNameAuth', realNameAuthenticationPassed)
            resolve(true)
          },
          fail: (error) => {
            console.log('getPatientInfo error:', error)
            resolve(true)
          }
        })
      } else {
        console.log('没有获取到patientId')
        resolve(true)
      }
    })
  }
  function getWhToken(token) {
    return new Promise((resolve) => {
      whRequest({
        noAuth: true,
        url: '/app/whToken',
        data: {
          appToken: token
        },
        method: 'GET',
        success: async (data) => {
          console.log('getWhToken success:',data)
          let { accessToken, userId } = data
          Taro.setStorageSync('whToken', accessToken)
          Taro.setStorageSync('patientId', userId)
          // 获取用户是否已经激活
          await getPatientInfo(userId)
          resolve(true)
        },
        fail: (err) => {
          console.log('getWhToken fail:', err)
          resolve(true)
        },
        
      })
    })
  }
  // 授权获取手机号
  function getPhoneNumberCallback(e) {
    // console.log('getPhoneNumberCallback:',e)
    Taro.showLoading({
      title: '登录中...',
      mask: true
    })
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      // 获取微信手机号
      request({
        url: '/wechatApp/phone',
        noAuth:true,
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          code: e.detail.code,
          appid: appid,
        },
        method: 'GET',
        success: function (respData) {
          // console.log('phone respData:',respData)
          custPhone = respData.phoneNumber
          Taro.setStorageSync('custPhone', respData.phoneNumber)
          Taro.login({
            success: (loginRes) => {
              if (loginRes.code) {
                // 获取用户信息
                Taro.getUserInfo({
                  success: function (innerRes) {
                    // console.log('getUserInfo innerRes:',innerRes)
                    userInfo = innerRes.userInfo

                    Taro.setStorage({
                      key: 'userInfo',
                      data: userInfo
                    })
                    // console.log('wxlogin innerRes:',innerRes)
                    // 获取用户openId
                    request({
                      url: '/wechatApp/getOpenId',
                      data: {
                        code: loginRes.code,
                        appid: appid,
                      },
                      method: 'GET',
                      success: function (respData) {
                        // console.log('getOpenId respData:', respData)
                        openid = respData.openid
                        unionid = respData.unionid
                        Taro.setStorageSync('openid', openid)
                        Taro.setStorageSync('unionid', unionid)
                        // 注册或者更新用户信息
                        uploadUserInfo()
                        // serverLogin()
                       
                      },
                      fail: function (err) {
                        Taro.hideLoading()
                        Taro.showToast({
                          title: '获取openid失败',
                          icon: 'none'
                        })
                      }
                    })
                  }
                })
                
              } else {
              }
            },
          })
        },
        fail: function (err) {
          Taro.hideLoading()
        }
      })
      }else {
        Taro.hideLoading()
        Taro.showToast({
          title: '获取手机号失败',
          icon: 'none'
        })
      }

  }

  function uploadUserInfo(){
    var info = {
      openId:openid,
      custName: userInfo.nickName,
      weixinUserHeaderUrl: userInfo.avatarUrl,
      sex: userInfo.gender,
      custPhone: custPhone,
    }
    // console.log('info:',info)
    // 这个接口既是注册，也是更新
    request({
      url: '/api/CustBasicInfo/regUser',
      data: info,
      method: 'post',
      success: function (res) {
        // console.log('regUser res:',res)
        // 注册或者更新成功后再获取tokne
        weChatLogin()
      }
    })
  }
  function getUser(){
    return new Promise((resolve,reject)=>{
      request({
        url: '/api/my/show',
        method: 'get',
        success: function (respData) {
          let custBasicInfo = respData.custBasicInfo
          Taro.setStorageSync('user', {
            id: custBasicInfo.id,
          })
          resolve(respData)
          
        },
        fail: (error) => {
          // console.log('getUser fail:',error)
          resolve({})
        }
      })
    })
    
  }
  function isAgreeResult(shareToType, groupId, clientType) {
    //同意加入群
    return new Promise((resolve)=>{
      let url = ''
      if (shareToType == 10) {
        url ='/api/points/family/agree/' +
          groupId +
          '/' +
          clientType +
          '/' +
          openid
      } else if (shareToType == 11) {
        url =
          '/api/points/family/disAgree/' +
          groupId +
          '/' +
          clientType +
          '/' +
          openid
      }
      if(url === ''){
        resolve(true)
        return 
      }
      // console.log('login isAgreeResult url:', url)
      request({
        url: url,
        data: {
          token:Taro.getStorageSync('token'),
          openId: openid
        },
        method: 'post',
        success: function (res) {
          Taro.removeStorageSync('inviteObj')
          
        },
        
        complete:()=>{
          resolve(true)
        }
      })
    })

  }
  function weChatLogin() {
    let that = this
    //start request
    request({
      url: '/api/CustBasic/userOpenIdLogin/' + openid,
      data: {},
      method: 'post',
      header: {
        'content-type': 'application/json'
      },
      success: async function (respData,data) {
        // console.log('weChatLogin data:',data)
        
        Taro.setStorageSync('token', data.token)
        // 获取用户金币值
        // 获取万户token
        await Promise.all([getUser(),isAgreeResult(
          inviteOptions.shareToType,
          inviteOptions.groupId,
          inviteOptions.clientType,
        ),getWhToken(data.token)])
        
        if (inviteOptions.shareToType == 10) {
          Taro.setStorageSync('inviteAgree',1)
          //未登录同意加入群
        }
        Taro.hideLoading()
        
        // console.log('fromPath:',fromPath)
        if(props.successCallback){
          props.successCallback()
        }else {
          Taro.reLaunch({
            url: fromPath,
            success: function (res) {},
            fail: function (error) {
              console.log('error:', error)
            },
            complete: function (res) {
              Taro.showToast({
                title: '登录成功',
                icon: 'success'
              })
            }
          })
        }
      },
      fail: function (err) {
        Taro.hideLoading()
        console.log('weChatLogin err:', err)
      }
    })
  }

  function agreePrivacyAuthorizationCallback(e){
    console.log('agreePrivacyAuthorizationCallback e:',e)
    Taro.eventCenter.trigger('agreePrivacyAuthorizationCallback')
  }
  return (
    <View className={['user-login',visible ? 'show' : 'hide'].join(' ')}>
      <View className='userlogin-content'>
        {/* <View className='title'>{props.title}</View> */}
        <View className='bodyer'>
          {props.content}
        </View>
        <View className='footer'>
          <Button type='default' size='mini' onClick={()=>{ props.cancel()}}>取消</Button>
          <Button className='btn' size='mini' type='primary' openType='getPhoneNumber|agreePrivacyAuthorization' onGetPhoneNumber={getPhoneNumberCallback} onAgreePrivacyAuthorization={agreePrivacyAuthorizationCallback}  onClick={()=>{
            props.close()
          }}>{props.btnText}</Button>

        </View>
      </View>
      
    </View>
  )
}